/**
 * @file difyChat.js
 * @description Dify智能助手API服务
 * @created 2024-07-16
 */

import axios from 'axios';

// Dify API配置
const DIFY_API_KEY = 'app-zWTMgCLb1yICdF0Vv1JE8E1S';
const DIFY_API_URL = 'http://121.40.242.43/v1';

// 创建一个axios实例，预设Authorization头
const difyAxios = axios.create({
  baseURL: DIFY_API_URL,
  headers: {
    'Authorization': `Bearer ${DIFY_API_KEY}`,
    'Content-Type': 'application/json'
  }
});

export const difyAPI = {
  /**
   * 发送消息（阻塞模式）
   * @param {string} query - 用户输入的文本
   * @param {string} conversationId - 对话ID，用于继续对话
   * @param {string} userId - 用户标识
   * @param {object} inputs - 可选的变量输入
   * @returns {Promise} API响应
   */
  sendMessage(query, conversationId = '', userId = 'default_user', inputs = {}) {
    return difyAxios.post('/chat-messages', {
      query,
      conversation_id: conversationId,
      user: userId,
      inputs,
      response_mode: 'blocking'
    });
  },
  
  /**
   * 发送消息（流式模式）
   * @param {string} query - 用户输入的文本
   * @param {string} conversationId - 对话ID，用于继续对话
   * @param {string} userId - 用户标识
   * @param {object} inputs - 可选的变量输入
   * @returns {Promise<Response>} Fetch API响应，用于处理SSE
   */
  async sendStreamingMessage(query, conversationId = '', userId = 'default_user', inputs = {}) {
    const response = await fetch(`${DIFY_API_URL}/chat-messages`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${DIFY_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        query,
        conversation_id: conversationId,
        user: userId,
        inputs,
        response_mode: 'streaming'
      })
    });
    
    return response;
  },
  
  /**
   * 处理SSE流式响应
   * @param {Response} response - fetch API的响应对象
   * @param {function} onMessage - 消息处理回调
   * @param {function} onError - 错误处理回调
   * @param {function} onEnd - 结束处理回调
   */
  handleStreamResponse(response, onMessage, onError, onEnd) {
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
    }
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    
    function processStream() {
      return reader.read().then(({ done, value }) => {
        if (done) {
          if (buffer.trim()) {
            // 处理缓冲区中剩余的数据
            processChunk(buffer);
          }
          if (onEnd) onEnd();
          return;
        }
        
        // 解码并添加到缓冲区
        buffer += decoder.decode(value, { stream: true });
        
        // 按 data: 行分割并处理
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || ''; // 最后一行可能不完整，保留在缓冲区
        
        lines.forEach(processChunk);
        
        // 继续读取流
        return processStream();
      }).catch(error => {
        if (onError) onError(error);
      });
    }
    
    function processChunk(chunk) {
      // 移除 "data: " 前缀
      const dataString = chunk.replace(/^data: /, '');
      if (!dataString.trim()) return;
      
      try {
        const data = JSON.parse(dataString);
        
        if (data.event === 'error') {
          if (onError) onError(new Error(data.message || '未知错误'));
          return;
        }
        
        if (onMessage) onMessage(data);
      } catch (error) {
        console.error('解析SSE数据出错:', error, dataString);
        if (onError) onError(error);
      }
    }
    
    // 开始处理流
    processStream();
  },
  
  /**
   * 测试Dify API连接
   * @returns {Promise} 测试结果
   */
  testConnection() {
    return difyAxios.get('/');
  }
};

export default difyAPI; 